﻿using DAL.Comm;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class SystemUserDAL
    {
        private SqlCommand cmd;
        public SystemUserDAL()
        {
            cmd = new SqlCommand();
            cmd.CommandType = CommandType.StoredProcedure;
        }
        private string GetMD5(string password)
        {
            if (password == null)
                return null;
            MD5 md5HasherString = MD5.Create();
            byte[] data = md5HasherString.ComputeHash(Encoding.Default.GetBytes(password));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }            

            return sBuilder.ToString();
        }
        /// <summary>
        /// 用户登录实现
        /// </summary>
        public bool UserLogin(string UserID, string Password)
        {
            cmd.CommandText = "FindPWDByUserID";
            string pwdString = "0x"+GetMD5(Password);
            cmd.Parameters.Clear();
            cmd.Parameters.Add("UserID", SqlDbType.NVarChar, 6).Value = UserID;
            cmd.Parameters.Add("Password", SqlDbType.NVarChar, 50).Value = pwdString;

            int num;
            try
            {
                num = (int)SQLHelper.GetScalar(cmd);
                if (num > 0)
                    return true;
                else return false;

            }
            catch //(Exception ex)
            {
                return false;
            }
        }

        public List<SystemUser> GetList()
        {
            cmd.CommandText = "SelectSystemUserList";//指定存储过程名称
            cmd.Parameters.Clear();//清空存储过程参数列表

            List<SystemUser> list = new List<SystemUser>();//定义泛型集合用于存储数据库返回数据

            SqlDataReader read = SQLHelper.ExcuteReader(cmd);//调用通用数据访问类进行读库操作
            while (read.Read())
            {
                SystemUser bo = new SystemUser();//实例化Category类，用于存储一条产品类型记录
                bo.UserID = read["UserID"].ToString().Trim();//将当前循环的记录列名为CategoryID的数据值赋值给bo.CategoryID
                bo.BaseFunction = int.Parse(read["BaseFunction"].ToString());
                bo.PurchaseFunction = int.Parse(read["PurchaseFunction"].ToString());
                bo.SaleFunction = int.Parse(read["SaleFunction"].ToString());
                bo.UserFunction = int.Parse(read["UserFunction"].ToString());

                list.Add(bo);//将当前记录添加至泛型集合list中
            }
            read.Close();//关闭读库
            return list;
        }

    
    }
}
